#!/bin/bash

# 获取当前用户信息
USERNAME=$(whoami)
USER_UID=$(id -u)
USER_GID=$(id -g)
IMAGE_NAME="ubuntu_tee"
IMAGE_TAG="1.0"
CONTAINER_NAME="my_container"
PRODUCT="$1"

# 确保当前环境中存在 code_root 和 LOCAL_BRANCH 变量
if [ -z "$code_root" ]; then
    echo "Error: code_root environment variable is not set."
    exit 1
fi

if [ -z "$LOCAL_BRANCH" ]; then
    echo "Error: LOCAL_BRANCH environment variable is not set."
    exit 1
fi

function _setting() {
    # 你的设置代码
    echo "设置代码执行中..."
    return 0 # 假设设置代码成功
}

function _build_docker() {
    # 构建 Docker 镜像时传递用户信息
    docker build \
        --build-arg USERNAME="${USERNAME}" \
        --build-arg USER_UID="${USER_UID}" \
        --build-arg USER_GID="${USER_GID}" \
        -t "${IMAGE_NAME}:${IMAGE_TAG}" .

    # 通过 docker images 命令检查镜像是否存在
    if docker images | grep -q "${IMAGE_NAME}"; then
        # 提示构建成功
        echo "Docker image '${IMAGE_NAME}:${IMAGE_TAG}' built successfully with user ${USERNAME} (UID: ${USER_UID}, GID: ${USER_GID})"
    else
        # 提示构建失败
        echo "Failed to build Docker image '${IMAGE_NAME}:${IMAGE_TAG}'."
        return 1
    fi
}

function _run_docker() {
    if docker ps -a | grep -q "${CONTAINER_NAME}"; then
        echo "已存在容器，删除容器 ${CONTAINER_NAME}"
        docker rm "${CONTAINER_NAME}"
    fi

    docker run --name "${CONTAINER_NAME}" \
        -e code_root="$code_root" \
        -e LOCAL_BRANCH="$LOCAL_BRANCH" \
        -e PRODUCT="$PRODUCT" \
        "${IMAGE_NAME}:${IMAGE_TAG}" \
        tail -f /dev/null

    # 检查 Docker 运行结果
    if [ $? -ne 0 ]; then
        echo "Failed to run Docker container '${CONTAINER_NAME}'."
        return 1
    fi
}

function main() {
    if ! _setting; then
        echo "Setting step failed."
        return 1
    fi

    if ! _build_docker; then
        echo "Docker build step failed."
        return 1
    fi

    if ! _run_docker; then
        echo "Docker run step failed."
        return 1
    fi

    echo "当前的目录是：$(pwd)"

}

main "$1"
